<template>
	<view>
		<view class="picker-body">
			<picker-view class="picker-view" :value="valueArr" @change="change" @touchend="touchend">
				<picker-view-column v-if="params.year">
					<view class="column-item display-flex align-items-center space-center"
						v-for="(item,index) in years" :key="index">
						<text class="column-item-text">{{item}}年</text>
					</view>
				</picker-view-column>
				<picker-view-column v-if="params.month">
					<view class="column-item display-flex align-items-center space-center"
						v-for="(item,index) in months" :key="index">
						<text class="column-item-text">{{formatNumber(item)}}月</text>
					</view>
				</picker-view-column>
				<picker-view-column v-if="params.day">
					<view class="column-item display-flex align-items-center space-center"
						v-for="(item,index) in days" :key="index">
						<text class="column-item-text">{{formatNumber(item)}}日</text>
					</view>
				</picker-view-column>
				
				<!-- <picker-view-column v-if="params.half">
				<view class="column-item" v-for="(item,index) in halfs" :key="index">
					<text class="column-item-text">{{item.label}}</text>
				</view>
			</picker-view-column> -->
			</picker-view>
			<span class="model-buttons-footer">
				<button class="model-buttons1"  @click="closeDate">取消</button>
				<button class="model-buttons2"  @click="getResult">确定</button>
			</span>
		</view>
	</view>
</template>

<script>
	import timeFormat from "./timeFormat.js"
	export default {
		props: {
			// picker中需要显示的参数
			params: {
				type: Object,
				default () {
					return {
						year: true,
						month: true,
						day: true,
						half: !false
					};
				}
			},
			// 默认显示的时间，2025-07-02 || 2025-07-02 13:01:00 || 2025/07/02
			defaultTime: {
				type: String,
				default: timeFormat(new Date(), 'yyyy-mm-dd')
			},
			// 自定义时间选项模式month:月 day:天
			optionMode: {
				type: String,
				default: 'month'
			},
			//选择器模式 single:单月 multiple:多月 all:都包括(暂时有bug 勿用)
			mode: {
				type: String,
				default: 'all'
			},
			endTime: {
				type: String,
				default: timeFormat(new Date(), 'yyyy-mm-dd')
			},
			successStartTime: {
				type: String,
				default: timeFormat(new Date(), 'yyyy-mm-dd')
			},
			successEndTime: {
				type: String,
				default: timeFormat(new Date(), 'yyyy-mm-dd--')
			},
		},
		data() {
			return {
				timeFormat,
				years: [],
				months: [],
				days: [],
				halfs: [{
					label: '上午',
					value: 1
				}, {
					label: '下午',
					value: 2
				}],
				valueArr: [],
				yearKey: 0,
				monthKey: 0,
				dayKey: 0,
				halfKey: 0,
				date: '',
				startDate: '',
				endDate: '',
				time: {},
				end_time: {},
				tabs: ['月份选择', '自定义'],
				tabIndex: 0,
				opIndex: -1,
				op1Index: 0,
				options: ['近一个月', '近三个月', '近半年', '近一年', '近两年'],
				fmt: 'yyyy-mm-dd',
				isClick: false,
			}
		},
		mounted() {
			this.init();
		},
		watch: {
			'time.year'(val, oval) {
				if (this.params.month && oval) {
					this.setMonths()
					// this.setDays()
				}
				if (this.params.day && oval) {
					this.setDays()
				}
			},
			'time.month'(val, oval) {
				if (this.params.day && oval) {
					this.setDays()
				}
			},
		},
		methods: {
			closeDate(){
				this.$emit('show', false);
			},
			init() {
				this.valueArr = [];
				this.tabIndex = this.mode == 'multiple' ? 1 : 0
				// 初始化默认选中时间
				this.time = this.initTimeValue(this.defaultTime);
				// 初始化截止时间
				this.end_time = this.initTimeValue(this.endTime);
				let fmt = []
				if (this.optionMode == 'day') {
					this.options = ['近3天', '近7天', '近15天']
				}
				if (this.params.year) {
					this.valueArr.push(0);
					this.yearKey = this.valueArr.length - 1
					this.setYears();
					fmt.push('yyyy')
					fmt.push('-')
				}
				if (this.params.month) {
					this.valueArr.push(0);
					this.monthKey = this.valueArr.length - 1
					this.setMonths();
					fmt.push('mm')
					fmt.push('-')
				}
				if (this.params.day) {
					this.valueArr.push(0);
					this.dayKey = this.valueArr.length - 1
					this.setDays();
					fmt.push('dd')
				}
				if (this.params.half) {
					this.valueArr.push(0);
					this.halfKey = this.valueArr.length - 1
				}
				this.fmt = fmt.join('')
				// 根据需求做的数据处理
				let currentDate = new Date();
				if (this.successStartTime || this.successEndTime) {
					if (this.tabIndex == 0) {
						this.date = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt)
					} else {
						this.startDate = this.changeDateFmt(this.successStartTime);
						this.date = this.endDate = this.changeDateFmt(this.successEndTime);
					}
				} else {
					// 开始时间为一个月的月初
					currentDate.setDate(1);
					this.startDate = this.timeFormat(currentDate, this.fmt);
					this.date = this.endDate = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt)
				}
				this.optionChange(0);
			},
			initDate() {
				if (this.params.year) {
					this.setYears();
				}
				if (this.params.month) {
					this.setMonths();
				}
				if (this.params.day) {
					this.setDays();
				}
			},
			open() {
				// this.$refs.popup.open('bottom')
			},
			close() {
				uni.showLoading({
					title: '加载中'
				});
				this.$emit('close');
				// this.$refs.popup.close()
			},
			//点击重置
			reset() {
				this.close();
				this.init()
				this.$emit('reset');
			},
			// 点击确定
			getResult() {
				let result = {};
				let {
					date,
					time,
					halfs,
					halfKey,
					valueArr
				} = this
				if (this.tabIndex) {
					let change_date = this.endDate
					let start_time = {}
					let end_time = {}
					if (this.changeDateT(this.startDate) > this.changeDateT(this.endDate)) {
						this.endDate = this.startDate
						this.startDate = change_date
						this.optionChange(0)
					}
					if (this.params.year) {
						start_time.year = this.formatNumber(this.initTimeValue(this.startDate).year || 0);
						end_time.year = this.formatNumber(this.initTimeValue(this.endDate).year || 0);
					}
					if (this.params.month) {
						start_time.month = this.formatNumber(this.initTimeValue(this.startDate).month || 0);
						end_time.month = this.formatNumber(this.initTimeValue(this.endDate).month || 0);
					}
					if (this.params.day) {
						start_time.day = this.formatNumber(this.initTimeValue(this.startDate).day || 0);
						end_time.day = this.formatNumber(this.initTimeValue(this.endDate).day || 0);
					}
					start_time.time = this.changeDateG(this.startDate);
					end_time.time = this.changeDateG(this.endDate);
					start_time.timestamp = new Date(this.changeDateT(this.startDate)).getTime();
					end_time.timestamp = new Date(this.changeDateT(this.endDate)).getTime();
					result = {
						start_time,
						end_time
					}
				} else {
					if (this.params.year) result.year = this.formatNumber(time.year || 0);
					if (this.params.month) result.month = this.formatNumber(time.month || 0);
					if (this.params.day) result.day = this.formatNumber(time.day || 0);
					result.time = date.substring(0, 7)
					// result.half = halfs[valueArr[halfKey]].value
					result.timestamp = new Date(this.changeDateT(date)).getTime();
				}
				console.log(result, 'result')
				this.$emit('confirm', result);
			},
			// 设置picker的某一列值
			setYears() {
				let {
					time,
					end_time
				} = this
				let {
					year
				} = end_time
				// 获取年份集合
				this.years = this.generateArray(1900, 2099);
				// 设置this.valueArr某一项的值，是为了让picker预选中某一个值
				setTimeout(() => {
					this.valueArr.splice(this.yearKey, 1, this.getIndex(this.years, time.year));
				}, 10)

			},
			setMonths() {
				let {
					time,
					end_time
				} = this
				let {
					year,
					month
				} = end_time
				if (year == time.year && this.params.year) {
					this.months = this.generateArray(1, month);
				} else {
					this.months = this.generateArray(1, 12);
				}
				if (time.month > this.months.length) this.time.month = this.months.length;
				//解决微信小程序初始化问题
				setTimeout(() => {
					this.valueArr.splice(this.monthKey, 1, this.getIndex(this.months, time.month));
				}, 10)


			},
			setDays() {
				let {
					time,
					end_time
				} = this
				let {
					year,
					month,
					day
				} = end_time
				let totalDays = new Date(time.year, time.month, 0).getDate();
				if (year == time.year && month == time.month && this.params.year) {
					this.days = this.generateArray(1, day);
				} else {
					this.days = this.generateArray(1, totalDays);
				}
				if (time.day > this.days.length) this.time.day = this.days.length;
				setTimeout(() => {
					this.valueArr.splice(this.dayKey, 1, this.getIndex(this.days, time.day));
				}, 10)

			},
			// 生成递进的数组
			generateArray: function(start, end) {
				// 转为数值格式，否则用户给end-year等传递字符串值时，下面的end+1会导致字符串拼接，而不是相加
				start = Number(start);
				end = Number(end);
				end = end > start ? end : start;
				// 生成数组，获取其中的索引，并剪出来
				return [...Array(end + 1).keys()].slice(start);
			},
			getIndex: function(arr, val) {
				let index = arr.indexOf(val);
				// 如果index为-1(即找不到index值)，~(-1)=-(-1)-1=0，导致条件不成立
				return ~index ? index : 0;
			},
			//日期时间处理
			initTimeValue(defaultTime) {
				defaultTime = this.changeDateT(defaultTime);
				// 格式化时间，在IE浏览器(uni不存在此情况)，无法识别日期间的"-"间隔符号
				let fdate = defaultTime.replace(/\-/g, '/');
				fdate = fdate && fdate.indexOf('/') == -1 ? `2020/01/01 ${fdate}` : fdate;
				let time = null;
				if (fdate) time = new Date(fdate);
				else time = new Date();
				// 获取年日月时分秒
				return {
					year: time.getFullYear(),
					month: Number(time.getMonth()) + 1,
					day: time.getDate(),
				}
			},
			// 小于10前面补0，用于月份，日期，时分秒等
			formatNumber(num) {
				return +num < 10 ? '0' + num : String(num);
			},
			// 获取时间戳
			getTimestamp(dateObj) {
				// yyyy-mm-dd为安卓写法，不支持iOS，需要使用"/"分隔，才能二者兼容
				// let time = date.year + '/' + date.month + '/' + (date.day || '01');
				// return new Date(time).getTime();
				// 假设 dateObj 是一个具有 year, month, day 属性的对象
				let timeString = `${dateObj.year}/${dateObj.month}/${(dateObj.day || '01')}`;
				return new Date(timeString); // 返回 Date 对象而不是时间戳
			},
			touchend(e) {
				this.opIndex = -1
			},
			// 用户更改picker的列选项
			change(e) {
				this.valueArr = e.detail.value;
				let i = 0;
				let time = {
					year: 0,
					month: 0,
					day: 0,
				}
				if (this.params.year) time.year = this.years[this.valueArr[i++]];
				if (this.params.month) time.month = this.months[this.valueArr[i++]];
				if (this.params.day) time.day = this.days[this.valueArr[i++]];
				this.time = time
				// let date = this.timeFormat(this.getTimestamp(time), this.fmt)
				let date = this.timeFormat(this.getTimestamp({ year: this.params.year, month: this.params.month, day: this.params.day }), this.fmt);
				//自定义时间段
				if (this.tabIndex) {
					if (this.op1Index) {
						this.endDate = date;
					} else {
						this.startDate = date;
					}
				} else { //月份选择
					this.date = date;
				}
			},
			tabChange(i) {
				this.tabIndex = i
				if (!i) {
					this.time = this.initTimeValue(this.date);
					this.date = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt)
					this.initDate()
				} else {
					let currentDate = new Date();
					currentDate.setDate(1);
					this.startDate = this.timeFormat(currentDate, this.fmt);
					this.date = this.endDate = this.timeFormat(new Date(this.defaultTime.replace(/\-/g, '/')), this.fmt);
					this.optionChange(0)
				}
			},
			//选择快捷时间段
			optionSelect(i) {
				this.opIndex = i;
				let end_time = new Date(); // 当前日期作为结束日期  
				let start_time;
				switch (i) {
					case 0: // 近一个月
						start_time = new Date(end_time);
						start_time.setMonth(end_time.getMonth() - 1); // 设置月份为前一个月  
						break;
					case 1: // 近三天 或 近三个月  
						if (this.optionMode === 'day') {
							start_time = new Date(end_time);
							start_time.setDate(end_time.getDate() - 3); // 近三天  
						} else {
							start_time = new Date(end_time);
							start_time.setMonth(end_time.getMonth() - 3); // 近三个月  
						}
						break;
					case 2: // 近七天 或 近六个月（注意：原始代码是近半年，但通常半年为6个月）  
						if (this.optionMode === 'day') {
							start_time = new Date(end_time);
							start_time.setDate(end_time.getDate() - 7); // 近七天  
						} else {
							start_time = new Date(end_time);
							start_time.setMonth(end_time.getMonth() - 6); // 近六个月  
						}
						break;
					case 3: // 近十五天 或 近一年  
						if (this.optionMode === 'day') {
							start_time = new Date(end_time);
							start_time.setDate(end_time.getDate() - 15); // 近十五天  
						} else {
							start_time = new Date(end_time);
							start_time.setFullYear(end_time.getFullYear() - 1); // 近一年  
						}
						break;
					case 4: // 近两年  
						start_time = new Date(end_time);
						start_time.setFullYear(end_time.getFullYear() - 2); // 近两年  
						break;
				}
				// 格式化日期并赋值给startDate和endDate  
				this.endDate = this.timeFormat(end_time, this.fmt);
				this.startDate = this.timeFormat(start_time, this.fmt);
				this.time = this.initTimeValue(this.startDate);
				// 初始化日期或其他相关操作  
				this.initDate();
				this.getResult()
			},
			//起始时间、截至时间切换
			optionChange(i) {
				this.op1Index = i
				this.time = this.initTimeValue(i ? this.endDate : this.startDate);
				this.initDate()
			},
			changeDateFmt(dateT) {
				let s = dateT.split("-");
				return s[0] + "年" + s[1] + "月" + s[2] + "日";
			},
			changeDateT(dateT) {
				let s = dateT.replace(/[年,月,日]/g, '/').substring(0, 10);
				return s;
			},
			changeDateG(dateT) {
				let s = dateT.replace(/[年,月,日]/g, '-').substring(0, 10);
				return s;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.model-buttons1{
		background-color: #fff;
		color: black;
		border-radius: 4px;
		box-sizing: border-box;
		border: none;
		outline: none;
		height: 40px;
		line-height: 40px;
		margin-left: 10px;
	}
	.model-buttons2{
		margin-right: 15px;
		background-color: #fff;
		color: black;
		border-radius: 4px;
		box-sizing: border-box;
		border: none;
		outline: none;
		height: 40px;
		line-height: 40px;
	}
	.model-buttons-footer{
		display: inline-flex;
		align-items: center; /* 垂直居中 */
		line-height: 30px;
		border-top: 1px solid #ccc;
		position: relative;
		top: 15px;
		width: 300px;
		height: 50px;
	}
	.flex {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.row-between {
		justify-content: space-between;
	}

	.popup-box {
		background-color: #fff;
		padding: 0 0 20rpx 0;
	}

	.picker-body {
		overflow: hidden;
		margin: 0 70rpx;
		padding: 40rpx 0;
	}

	.picker-view {
		height: 280rpx;
	}

	.column-item {
		font-size: 30rpx;
		color: black;
		font-weight: 400;

	}

	.column-item-text {
		line-height: 38px;
		height: 38px;
		font-size: 32rpx;
	}

	.title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
		position: relative;

		.close {
			position: relative;
			right: 50rpx;
		}

		.title-text {
			width: 750rpx;
			padding: 24rpx 0;
			display: flex;
			flex-direction: row;
			justify-content: center;

			.text {
				font-size: 32rpx;
				font-weight: 600;
			}
		}
	}

	.tabs-box {
		width: 100%;
		display: flex;
		flex-direction: row;

		.tabs-item:nth-child(2) {
			padding: 0 0 10rpx 98rpx;
		}

		.tabs-item:nth-child(1) {
			padding: 0 0 10rpx 50rpx;
		}

		.item-text {
			color: #2C2C2C;
			font-size: 24rpx;
			font-weight: 500;
		}
	}

	.tabs-check {

		// border-bottom: 4rpx solid #1DAA9F !important;
		.item-text {
			color: #116C40;
			font-size: 24rpx;
			font-weight: 400;
		}
	}

	.bottom {
		padding: 0 32rpx 32rpx;
		display: flex;
		align-items: center;
		flex-direction: row;

		.h-btn {
			flex: 1;
		}

		.resetClear {
			width: 166px;
			height: 42px;
			line-height: 42px;
			border-radius: 22px;
			border: 1px solid black;
			font-weight: 400;
			font-size: 16px;
			color: black;
			text-align: center;
			margin-right: 10px;
		}

		.confirm {
			width: 166px;
			height: 42px;
			line-height: 42px;
			background: linear-gradient(96deg, #4375D8 0%, #85B9FF 100%);
			border-radius: 22px;
			font-weight: 400;
			font-size: 16px;
			color: #FFFFFF;
			text-align: center;
		}

	}

	.option {
		padding: 14rpx 58rpx;
		font-size: 24rpx;
		border-radius: 16rpx;
		background: #F6F5FA;
		display: flex;
		justify-content: center;
		flex-direction: row;

		.option-text {
			font-size: 24rpx;
			font-weight: 500;
			color: #333333;
			line-height: 40rpx;

		}
	}

	.timeStyle {
		min-width: 190rpx;
		height: 64rpx;
		line-height: 64rpx;
		background: #F7F6FB;
		border-radius: 16rpx;
		font-weight: 500;
		font-size: 24rpx;
		color: #333333;
		text-align: center;
		font-style: normal;
		text-transform: none;
		margin: 0 28rpx 28rpx 0;
		letter-spacing: 1px;
	}

	.timeStyle2 {
		position: relative;
		min-width: 190rpx;
		height: 64rpx;
		line-height: 64rpx;
		background: #E6F1EB;
		border-radius: 16rpx;
		font-weight: 500;
		font-size: 24rpx;
		color: #333333;
		text-align: center;
		font-style: normal;
		text-transform: none;
		margin: 0 28rpx 28rpx 0;

		&:after {
			content: '';
			position: absolute;
			right: -1px;
			bottom: -1px;
			width: 17.92px;
			height: 19.21px;
			background-size: cover;
		}
	}

	.option-check {
		background: #E6F1EB;
		border-radius: 16rpx;

		.option-text {
			color: #2E7356;
		}
	}

	.options-box {
		padding: 0 40rpx 20rpx 40rpx;
		transition-property: height;
		transition-duration: .4s;
	}

	.time-container {
		display: flex;
		flex-wrap: wrap;
	}

</style>
